/*
 * MainFrame.java
 *
 * Created on 9 de septiembre de 2007, 11:22
 */

package swagenda.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import org.apache.log4j.Logger;

import swagenda.data.Category;
import swagenda.exception.NotInitializedException;
import swagenda.proxy.OosProxy;
import swagenda.ui.components.SWAButton;
import swagenda.ui.components.SWALabel;
import swagenda.ui.components.SWAList;

/**
 * 
 * @author jorge
 */
@SuppressWarnings("serial")
public class MainFrame extends JFrame
{
	Logger logger = Logger.getLogger(this.getClass());
	public static MainFrame mainFrame;
	
	private JTabbedPane main;
	private OosProxy oosProxy;
	private ArrayList<AlphaPanel> panels;
	private JPanel nav;
	
	public SWAList sections;
	public SWAList tags;
	public SWAList locations;
	
	public MainFrame() throws HeadlessException
	{
		super();
		panels = new ArrayList<AlphaPanel>();
	}

	public void initComponents(OosProxy oosProxy)
	{
		this.oosProxy = oosProxy;
//		URL url = ClassLoader.getSystemResource("img/oos_invader.png");
//		Toolkit tk = Toolkit.getDefaultToolkit();
//		Image img = tk.getImage(url);
//		setIconImage(img);

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setTitle("swagenda 0.1");

		setJMenuBar(initMenus());
		add(initAlphas(), BorderLayout.CENTER);
		add(initNavPane(), BorderLayout.LINE_END);		
		
		pack();
	}
	
	public void reload()
	{
		ArrayList<Category> sectionsFilter = null;
		ArrayList<Category> tagsFilter = null;
		ArrayList<Category> locationsFilter = null;
		// retrieve the filters
		if (sections!=null) sectionsFilter = sections.selection();
		if (tags!=null) tagsFilter = tags.selection();
		if (locations!=null) locationsFilter = locations.selection();
		
		
		int i = 0;
		for (AlphaPanel ap: panels)
		{
			ap.init(oosProxy, i++, sectionsFilter, tagsFilter, locationsFilter);
			ap.revalidate();
			ap.repaint();
		}
	}
	
	private JPanel initNavPane()
	{
		JScrollPane listScroller;
		nav = new JPanel();
		nav.setLayout(new BoxLayout(nav, BoxLayout.PAGE_AXIS));
		
		JPanel buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
		SWAButton clear = new SWAButton("clear");
		SWAButton hide = new SWAButton("hide");
		buttons.add(clear);
		buttons.add(hide);
		buttons.setMaximumSize(new Dimension(150,100));
		nav.add(buttons);
		clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				clearFilters();
			}
		});
		hide.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				hideNavPanel();
			}
		});

		SWALabel lblSections = new SWALabel("sections");
		lblSections.setAlignmentX(Component.CENTER_ALIGNMENT);
		nav.add(lblSections);
		sections = new SWAList(oosProxy.owner.sections);
		listScroller = new JScrollPane(sections);
		listScroller.setPreferredSize(new Dimension(150, 0));		
		nav.add(listScroller);
		
		SWALabel lblTags = new SWALabel("tags");
		lblTags.setAlignmentX(Component.CENTER_ALIGNMENT);
		nav.add(lblTags);
		tags = new SWAList(oosProxy.owner.tags);
		listScroller = new JScrollPane(tags);
		listScroller.setPreferredSize(new Dimension(150, 0));		
		nav.add(listScroller);
		
		SWALabel lblLocations = new SWALabel("locations");
		lblLocations.setAlignmentX(Component.CENTER_ALIGNMENT);
		nav.add(lblLocations);
		locations = new SWAList(oosProxy.owner.locations);
		listScroller = new JScrollPane(locations);
		listScroller.setPreferredSize(new Dimension(150, 0));		
		nav.add(listScroller);
		
		return nav;
	}
	
	private void clearFilters()
	{
		logger.debug("clearing filters...");
		sections.clearSelection();
		tags.clearSelection();
		locations.clearSelection();
	}
	
	private void hideNavPanel()
	{
		logger.debug("hiding navPanel...");
		nav.setVisible(false);
	}
	
	private JTabbedPane initAlphas()
	{
		panels = new ArrayList<AlphaPanel>();
		main = new JTabbedPane(JTabbedPane.LEFT);
		//main.setFont(new Font(Font.DIALOG, Font.PLAIN, 14));
		logger.debug("initializing alphabetic panels");

		for (int i = 0; i < AlphaPanel.TAB_ARRAY.length; i++)
		{
			AlphaPanel ap = new AlphaPanel(oosProxy, i);
			panels.add(ap);
			JScrollPane scrollp = new JScrollPane(ap);
			scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
			scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
			main.addTab(AlphaPanel.TAB_ARRAY[i], scrollp);
			main.setMnemonicAt(i, AlphaPanel.MNEMONICS[i]);
		}
		return main;
	}

	private JMenuBar initMenus()
	{
		logger.debug("initializing menu");

		JMenuBar menuBar = new JMenuBar();
		JMenu oosMenu = new JMenu("11870");
		oosMenu.setFont(new Font(Font.DIALOG, Font.BOLD, 14));
		oosMenu.setMnemonic(KeyEvent.VK_1);
		menuBar.add(oosMenu);

		JMenuItem reloadMenuItem = new JMenuItem("reload", KeyEvent.VK_R);
		reloadMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
		oosMenu.add(reloadMenuItem);
		
		reloadMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				// reload the places from server
				oosProxy.reload();
				// reload the tabs
				reload();
			}
		});

		JMenuItem prefsMenuItem = new JMenuItem("preferences", KeyEvent.VK_P);
		prefsMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
		oosMenu.add(prefsMenuItem);
		prefsMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				PrefsDialog p = new PrefsDialog(MainFrame.mainFrame, oosProxy);
				p.pack();
				p.setVisible(true);
			}
		});

		JMenuItem filterMenuItem = new JMenuItem("filtering", KeyEvent.VK_S);
		filterMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
		oosMenu.add(filterMenuItem);
		filterMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				nav.setVisible(!nav.isVisible());
			}
		});

		JMenu wMenu = new JMenu("window");
		wMenu.setFont(new Font(Font.DIALOG, Font.BOLD, 14));
		wMenu.setMnemonic(KeyEvent.VK_W);
		JMenu lfMenu = new JMenu("look & feel");
		lfMenu.setMnemonic(KeyEvent.VK_L);
	    UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
		logger.debug("available lnf's:");
		for (int i = 0; i < info.length; i++)
		{
			String humanReadableName = info[i].getName();
			final String className = info[i].getClassName();
			logger.debug(humanReadableName+" -> "+className);
			JMenuItem lfsubmenu = new JMenuItem(humanReadableName);
			
			lfsubmenu.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					setLookAndFeel(className);
				}
			});
			lfMenu.add(lfsubmenu);
		}
		wMenu.add(lfMenu);
		menuBar.add(wMenu);
		
		return menuBar;
	}
	
	private void setLookAndFeel(String classname)
	{
		try
		{
			if (classname==null || classname.length()==0)
				classname = UIManager.getSystemLookAndFeelClassName();
			
			logger.debug("setting l&f -> "+classname);
			UIManager.setLookAndFeel(classname);
			SwingUtilities.updateComponentTreeUI(MainFrame.mainFrame);
		} catch (Exception e)
		{
			logger.error("could not set looknfeel", e);
		}
	}

	public static void main(String args[])
	{
		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				OosProxy oosProxy = new OosProxy();
				mainFrame = new MainFrame();

				try
				{
					oosProxy.init();
				} catch (NotInitializedException e)
				{
					PrefsDialog p = new PrefsDialog(mainFrame, oosProxy);
					p.pack();
					p.setVisible(true);
				}
				mainFrame.setLookAndFeel(null);
				mainFrame.initComponents(oosProxy);
				mainFrame.setVisible(true);
			}
		});
	}
}
